<?php
 

namespace App\Http\Controllers\Web\Member\Buyer;

use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;
use Exception;
use tech\core\Util;
use tech\core\eSign;


include(app_path() ."/Library/API/eSignOpenAPI.php");

class OrderContractController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'eqbao'],
        'show' => ['get', 'eqbao/%d'],
        'store' => ['post', 'eqbao'],
        'update' => ['put', 'eqbao/%d'],
        'find_by_userid'=>['get','eqbao/find_by_userid'],
        
        'contract_index' => ['get', 'buyer/order_contract'],
        'contract_show' => ['get', 'buyer/order_contract/%d'],
        'contract_store' => ['post', 'buyer/order_contract'],
        'contract_update' => ['put', 'buyer/order_contract/%d'],
        'find_by_orderid'=>['get','buyer/order_contract/find_by_orderid/%d'],
        
        'company_info'=>['get','seller/companymaterial/%d/showusercompany'],
        
        'order_show'  => ['get',  'buyer/service/orders/%d'],
        
        'contract_mb_index' => ['get', 'seller/contracts'],
        
        'sendmessage' => ['get', 'sendmessage'],
        
        'verifycode' => ['get', 'verifycode'],
        
        'qual_update' => ['post', 'buyer/attribute/%d'],
    ];
    

    protected $request;
    
    protected $sign;
    
    public function __construct(Request $request)
    {
        $this->request = $request;
        
        //实例化
        try {
            $this->sign = new eSign();
        } catch (Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }
    
    
    public function index(){
        $search_params = $this->request->all(['order_code', 'created_at','status','keyword']);
        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'page' => $page,
            'with' => 'orderProducts;shop',
            'orderBy'=>'id',
            'sortedBy'=>'desc',
        ];
        
        //请求部分
        $ret = http_web($this->api_url['contract_index'])->send($params);
        
        //结果处理部分
        $data = paginate($this->request, $ret['data']);
        
        //回填搜索框值
        $data['search_params'] = $search_params;
        
        return view('web.user.buyer.contract_orders',$data);
    }
    
    /**
     * 初始化和登录
     */
    
    public function init()
    {
        $iRet = $this->sign->init();
        if (0 === $iRet) {
            $array = array(
                "errCode" => 0,
                "msg" => "初始化成功",
                "errShow" => true
            );
            return response()->json($array);
        }
    }
    
  
    
    //合同授权
    public function contract_auth(){
        $result = http_web($this->api_url['find_by_userid'])->send();
        $data = [];
        if(isset($result['data'][0])){
            return redirect()->route('web.buyer.order_contract.index');
        }
        
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        $data['company_name']  = "";
        $data['company_address']  = "";
        
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['company_name'] = $company['company_name'];
            $data['company_address'] = $company['company_address'];
        }
        
        
        $data['mobile']=session('user_phone');
        
        return view('web.user.buyer.contract_admittance',$data);
    }
    
 
    
    public function contract_write(){
        $resp = ['status'=>0,'msg'=>""];
        $order_id = $this->request->post('order_id','');
        $qid = $this->request->post('qid','');
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        if(!isset($result['data'][0])){
            $resp['msg'] =  '请先授权合同';
            $resp['code'] = 1;
            return response()->json($resp);
        }
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        $data = [];
        if(isset($result['data'][0])){
            if($result['data'][0]['status']==1){
                return redirect()->route('web.buyer.order_contract.contract_cost',['order_id'=>$order_id,'seller_id'=>$result['data'][0]['seller_user_id']]);
            }
            $data = $result['data'][0];
        }else{
            $resp['msg'] = "卖家还未确认";
            return response()->json($resp);
        }
        $data['qid'] = $qid;
        old_set($data);
        
        return view('web.user.buyer.contract_write',$data);
    }
    
    public function contract_post(){
        $id = $this->request->get("id",0);
        $qid = $this->request->post('qid','');
        $data['buyer_user_id'] = session('user_id');
        $data['status'] = 1;
       
        
        $resp = ['status'=>0,'msg'=>""];
        $user_type =2;
        
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        
        $accountId = "";
        $sealData = "";
        
        if(!$qid){
            $resp['msg'] = "资质订单ID错误";
            return response()->json($resp);
        }
        
        if(isset($result['data']['0']['account_id'])){
            $accountId = $result['data'][0]['account_id'];
            $sealData = $result['data'][0]['yz_data'];
            
            if(!$sealData){
                $resp['msg'] = "请先创建印章";
                return response()->json($resp);
            }
        }else{
            $resp['msg'] = "请先合同授权";
            return response()->json($resp);
        }
        
        
        $result = http_web($this->api_url['contract_show'],[$id])->send();
        $order_id = 0;
        $contract_id = 0;
        $seller_id = 0;
        if(isset($result['data']['id'])){
            $contract_id = $result['data']['id'];
            $order_id = $result['data']['order_id'];
            $seller_id = $result['data']['seller_user_id'];
            if($result['data']['file_url'] ){
                $file_url=$result['data']['file_url'];
            }
            
            if($result['data']['status'] == 1){
                $resp['msg'] = '买家已签署合同';
                return response()->json($resp);
            }
        }else{
            $resp['msg'] = '卖家还未签署合同';
            return response()->json($resp);
        }
        
        if(!$file_url){
            $resp['msg'] = '待签署文件不能为空';
            return response()->json($resp);
        }
        
        $srcPdfFile=public_path($file_url) ; 
        $filename = pathinfo($srcPdfFile,PATHINFO_FILENAME);
        $dist_filename = "";
        if($filename){
            $dist_filename = 'uploads/'.$filename.'_final.pdf';
            $dstPdfFile=public_path($dist_filename);
        }
        
        $signType ='Key';// 'Single';
        $isQrcodeSign = $this->request->post('isQrcodeSign','');
        $signPos = array(
            'posPage' =>  -1,
            'posX' => 50,// 100,
            'posY' => -30,// 100,
            'key' =>   '甲方盖章',
            'width' => 0,
            'isQrcodeSign'  =>  false,
            'addSignTime'=>true,
        );
        $signFile = array(
            'srcPdfFile' => $srcPdfFile,
            'dstPdfFile' => $dstPdfFile,
            'fileName' =>  '',
            'ownerPassword' => ''
        );
        
        $ret = $this->sign->userSignPDF($accountId, $signFile, $signPos, $signType, $sealData, $stream = true);
    
        if(isset($ret['signServiceId'])){
            $data['file_url'] = $dist_filename;
            $data['web_url'] = asset($dist_filename);
            
            $data['buyer_sign_id'] = $ret['signServiceId'];
            $data['status'] = 1;
            $data['q_status'] = '3';
       
            $info = http_web($this->api_url['contract_update'],[$id])->send($data);
            
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['order_id'] =$order_id;
                $resp['seller_id'] =$seller_id;
                $resp['msg'] = $ret['msg'];
                
                $data['q_status'] = '3';
                $ret = http_web($this->api_url['qual_update'], [$qid])->send($data);
            }
        }else{
            $resp['msg'] = $ret['msg'];
        }
        
        
        return response()->json($resp);
    }
    
    public function contract_cost(){
        $order_id = $this->request->get('order_id','');
        $seller_id = $this->request->get('seller_id','');
        $data = [];
        
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
       
        if(!isset($result['data'][0]['status']) || $result['data'][0]['status'] == 0){
            $resp['msg'] = '还未签合同';
            return response()->json($resp);
        } 
        
        
        $ret = http_web($this->api_url['order_show'], [$order_id])->send();
   
        if(isset($ret['data']['user_id']) && $ret['data']['user_id']){
            $data['order_code'] = $ret['data']['order_code'];
            $data['order_money']=$ret['data']['order_money'];
            $info = http_web($this->api_url['company_info'],[$ret['data']['user_id']])->send();
            if(isset($info['data']['data'])){
                $data['buyer_user_name'] = $info['data']['data']['name'];
                $data['buyer_user_phone'] = $info['data']['data']['phone'];
                $data['buyer_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
                $data['buyer_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
                $data['buyer_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
            }
        }
        
        $info = http_web($this->api_url['company_info'],[$seller_id])->send();
      
        if(isset($info['data']['data'])){
            $data['seller_user_name'] = $info['data']['data']['name'];
            $data['seller_user_phone'] = $info['data']['data']['phone'];
            $data['seller_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
            $data['seller_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
            $data['seller_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
        }
        
        old_set($data);
        
        return view('web.user.buyer.contract_cost',$data);
    }
    
    public function sendsms(){
        $params = $this->request->all(['phone']);
        //发送短信验证
        $data_send = http_web($this->api_url['sendmessage'])->send($params);
        return response()->json($data_send);
    }
    
    public function contract_auth_post()
    {
        $resp = ['status'=>0,'msg'=>""];
        //$this->sign->init();
        $params = $this->request->all(['phone', 'name', 'organCode', 'regType', 'email', 'organType', 'legalArea', 'userType',
            'agentName', 'agentIdNo', 'legalName', 'legalIdNo','auth_card','company_address','code']);
        $params['regType'] = isset($params['regType']) ? $params['regType'] : 1;
        $verify_data = http_web($this->api_url['verifycode'])->send($params);
        if(isset($verify_data['code']) && $verify_data['code']==1){
            $resp['msg'] = $verify_data['message'];
            return response()->json($resp);
        }
        
        
        $ret = $this->sign->addOrganizeAccount(
            $params['phone'],
            $params['name'],
            $params['organCode'],
            $params['regType'] ,
            $params['email'],
            0,//$params['organType'],
            0,//$params['legalArea'] ,
            $params['userType'] ,
            $params['agentName'] ,
            $params['agentIdNo'] ,
            $params['agentName'],//$params['legalName'],对的相同赋值参数
            $params['agentIdNo'] ,//$params['legalIdNo'],对的相同赋值参数
            $address = '',
            $scope = '');
        
        $resp = ['status'=>0,'msg'=>$ret['msg']];
        if(isset($ret['accountId'])){
            $data['account_id'] = $ret['accountId'];
            $data['organ_code'] = $params['organCode'];
            $data['user_type'] = $params['userType'];
            $data['auth_name'] = $params['agentName'];
            $data['user_name'] = session("user_name");
            $data['auth_card'] = $params['agentIdNo'];
            $data['company_address'] = $params['company_address'];
            $data['company_name'] = $params['name'];
            
            $ret = $this->sign->addTemplateSeal(
                $ret['accountId'],
                'star',
                'red',
                '合同专用章',
                ''
                );
            if(isset($ret['imageBase64'])){
                $data['yz_data'] = $ret['imageBase64'];
            }
            
            $info = http_web($this->api_url['store'])->send($data);
            
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        }
        
        return response()->json($resp);
    }
    
     
    
   
    
    private function response($data){
        echo Util::jsonEncode($data);
        exit();
    }
  
   
}